package com.huatai.exchange.impl;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.DateFormatUtils;
import com.faneui.common.utils.ListUtils;
import com.google.common.collect.Maps;
import com.huatai.exchange.dal.dao.ExcDataFileInfoDAO;
import com.huatai.exchange.dal.dao.ExcExchangeDateFileDAO;
import com.huatai.exchange.dal.dao.ExcExchangeInfoDAO;
import com.huatai.exchange.dal.model.*;
import com.huatai.exchange.deal.FileCreateDealFactory;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.integration.base.service.FileOperateService;
import com.huatai.exchange.send.FileSendFactory;
import com.huatai.exchange.service.*;
import com.huatai.exchange.utils.FileDealUtils;
import com.huatai.exchange.utils.VelocityContextHelper;
import com.huatai.exchange.utils.VelocityUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ExcuteExchangeServiceImpl implements ExcuteExchangeService {

    private static final Logger logger = LoggerFactory.getLogger(ExcuteExchangeService.class);


    @Autowired
    private ExcExchangeInfoService excExchangeInfoService;

    @Autowired
    protected FileOperateService fileOperateService;

    @Autowired
    private ExcCustomerService excCustomerService ;

    @Autowired
    private ExcCommunicationService excCommunicationService ;

    @Autowired
    private ExcExchangeDateFileService excExchangeDateFileService;

    @Autowired
    private ExcDataFileInfoService excDataFileInfoService;

    @Autowired
    private VelocityContextHelper velocityHelper;

    @Autowired
    private FileCreateDealFactory dealFactory;

    @Autowired
    private FileSendFactory fileSendFactory;

    @Override
    public void executeExchangeDataFile(String exchangeInfoId, String occurDate) throws BusinessException {
        try {
            ExcExchangeInfo exchangeInfo = excExchangeInfoService.queryExcExchangeInfo(exchangeInfoId);
            ExcCustomer customer = excCustomerService.queryExcCustomer(exchangeInfo.getCustId());

            // 上下文 信息
            Map<String, Object> resvMap = Maps.newHashMap();
            resvMap.put(Contents.FIELD_YYYYMMDD, occurDate);
            resvMap.put("exchangeInfoId", exchangeInfoId);

            logger.info("完成文件准备："+ DateFormatUtils.HHmmss.format(new Date()));
            Velocity.init();
            VelocityContext context = velocityHelper.fillContext(resvMap);
            String beforeContent = exchangeInfo.getBeforeContent() ;

            if(StringUtils.isNotBlank(beforeContent)) {
                String checkResult = VelocityUtils.evaluate(context,beforeContent) ;
                // 交换校验指标 需要在这里标识
                if (!Contents.boolean_true.equals(checkResult)) {
                    throw new BusinessException(checkResult);
                }
            }

            getFileList(exchangeInfo,resvMap);

            String velocityContent = VelocityUtils.evaluate(context, exchangeInfo.getContent());
            if (!Contents.boolean_true.equals(velocityContent)) {
                throw new BusinessException(velocityContent);
            }

            // 多种传输方式
            List<ExcCommunication> coms = excCommunicationService.queryExcCommunicationList(exchangeInfoId);
            for (ExcCommunication com : coms) {
                fileSendFactory.getSendService(com.getCommunicationType())
                        .sendMessage(customer,resvMap);
            }

        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
    }

    private void getFileList(ExcExchangeInfo exchangeInfo, Map<String, Object> resvMap) throws BusinessException {
        logger.info("=============={}=============","开始准备文件");
        List<ExcExchangeDateFile> dataFileList = excExchangeDateFileService.queryExcExchangeDateFileList(exchangeInfo.getId());
        if (ListUtils.isEmpty(dataFileList))
            return ;
        StringBuffer fileNames = new StringBuffer("");
        StringBuffer filePaths = new StringBuffer("");
        //  遍历数据文件信息，获取文件
        for (ExcExchangeDateFile dateFile : dataFileList) {
            ExcDataFileInfo dataFileInfo = excDataFileInfoService.queryExcDataFileInfo(dateFile.getDataFileId());
            if(dataFileInfo == null)
                throw new BusinessException("数据文件ID["+dateFile.getDataFileId()+"]配置信息不存在") ;
            dealFactory.getDealService(dataFileInfo.getType()).downloadCreateFile(fileNames, filePaths, dateFile, dataFileInfo, resvMap);
        }
        logger.info("完成文件准备：" + DateFormatUtils.HHmmss.format(new Date()));
        // 压缩设置
        if (StringUtils.isBlank(filePaths.toString())) {
            return  ;
        }
        if (Contents.boolean_true.equals(exchangeInfo.getIsZip())) {

            filePaths = new StringBuffer(fileOperateService.uploadZipFiles(filePaths.toString().substring(1)
                    , fileNames.toString().substring(1), Contents.boolean_false));
            logger.info("重新压缩文件：" + DateFormatUtils.HHmmss.format(new Date()));
            fileNames = new StringBuffer(FileDealUtils.formatStr(exchangeInfo.getZipName(), null, resvMap));
            resvMap.put("fileNames", fileNames.toString());
            resvMap.put("filePaths", filePaths.toString());
        } else {
            resvMap.put("fileNames", fileNames.toString().substring(1));
            resvMap.put("filePaths", filePaths.toString().substring(1));
        }
    }
}
